package config;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import cn.zhang.action.PhoneAction;
import cn.zhang.dao.PhoneDao;
import cn.zhang.dao.PhoneDaoImpl;
import cn.zhang.entity.User;
import cn.zhang.service.PhoneService;

@Configuration
@EnableTransactionManagement
public class Config {

	@Bean(name="phoneDaoImpl")
	public PhoneDao getPhoneDao(){
		return new PhoneDaoImpl();
	}
	
	@Bean(name="phoneService")
	public PhoneService getPhoneService(){
		return new PhoneService();
	}
	
	
	@Bean(name="phoneAction")
	@Scope(value="prototype")
	public PhoneAction getPhoneAction(){
		
		return new PhoneAction();
	}
	
	@Bean(name="dataSource")
	public DriverManagerDataSource getDataSource(){
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///test");
		dataSource.setUsername("root");
		dataSource.setPassword("root");
		
		return dataSource;
	}
	
	@Bean
	public Properties getHibernateProperties(){
		Properties pro = new Properties();
		pro.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
		pro.setProperty("hibernate.hbm2ddl.auto", "update");
		pro.setProperty("hibernate.show_sql", "true");
		pro.setProperty("hibernate.format_sql", "true");
		pro.setProperty("hibernate.current_session_context_class", "thread");
		pro.setProperty("hibernate.format_sql", "true");
		pro.setProperty("mappingLocations", "cn.zhang.entity.Phone");
		
		return pro;
	}
	
	@Bean(name="sessionFactory")
	public LocalSessionFactoryBean getSessionFactory(){
		LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
		sessionFactory.setDataSource(getDataSource());
		sessionFactory.setConfigLocation(new ClassPathResource("hibernate.cfg.xml"));
		//sessionFactory.setHibernateProperties(getHibernateProperties());
		return sessionFactory;
	}
	
	@Bean(name="transactionManager")
	@Scope(value="prototype")
	public HibernateTransactionManager getTransactionManager(){
		return new HibernateTransactionManager(getSessionFactory().getObject());
	}
	
	@Bean(name="hibernateTemplate")
	public HibernateTemplate getHibernateTemplate(){
		
		return new HibernateTemplate(getSessionFactory().getObject());
	}
	
}